package com.blog.oguzhan.soapui.utils.datasource;

import com.eviware.soapui.model.testsuite.TestCase;
import com.eviware.soapui.model.testsuite.TestCaseRunner;

public class DatasourceLoop {

	private Datasource<?> datasource;
	private TestCase testCase;
	private TestCaseRunner testRunner;
	
	protected DatasourceLoop(TestCase testCase, TestCaseRunner testRunner, Datasource<?> datasource) {
		this.testCase = testCase;
		this.testRunner = testRunner;
		this.datasource = datasource;
		this.datasource.setDatasourceLoop(this);
	}
	
	public void iterate() {
		Datasource<?> ds = DatasourceFactory.getDatasource(testCase,datasource.getName());
		if(ds != null && ds.hasNext()) {
			try {
				datasource.iterate();
				testRunner.gotoStepByName(datasource.getName());
			} catch (IterationBrokenException e) {
				// ITERATION IS BROKEN; REMOVING EXISTING DATASOURCE
				breakLoop();
			}
		}
		else {
			// ITERATION IS FINISHED; REMOVE DATASOURCE
			breakLoop();
		}
	}
	
	protected void breakLoop() {
		DatasourceFactory.removeDatasource(testCase, datasource.getName());
	}
}
